package com.lp.security.schedule;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lp.biz.coupon.mapper.BizCouponMemberRelMapper;
import com.lp.biz.coupon.model.entity.BizCouponMemberRel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import static com.lp.common.constant.CommonConstant.NEGATE;
import static com.lp.common.constant.CouponConstant.STATUS_INVALID;
import static com.lp.common.constant.CouponConstant.STATUS_NOT_USED;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-07-23 23:42:50
 */
@Slf4j
@Component
public class CouponSchedule {

    @Autowired
    private BizCouponMemberRelMapper relMapper;

    /**
     * 项目启动后每隔3分31秒执行一次，错开其他定时任务
     */
    @Scheduled(fixedRate = (180 + 1) * 1000)
    public void checkExpireCoupon() {
        log.info("开始校验优惠券过期");
        relMapper.update(null, new UpdateWrapper<BizCouponMemberRel>().lambda()
                .eq(BizCouponMemberRel::getStatus, STATUS_NOT_USED)
                .eq(BizCouponMemberRel::getIsDeleted, NEGATE)
                .lt(BizCouponMemberRel::getEndAt, LocalDateTime.now())
                .set(BizCouponMemberRel::getStatus, STATUS_INVALID)
                .set(BizCouponMemberRel::getUpdateAt, LocalDateTime.now()));
        log.info("校验优惠券过期结束");
    }

    @Scheduled(fixedRate = (180 + 19) * 1000, initialDelay = 0)
    public void handOutBirthday() {
        log.info("开始分发生日优惠券");
        relMapper.handOutBirthday();
        log.info("生日优惠券结束");
    }
}
